package cn.jbooter.swagger.autoconfigure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import com.google.common.base.Predicate;

import cn.jbooter.swagger.autoconfigure.properties.ISwagger2Properties;

import com.google.common.base.Function;
import com.google.common.base.Optional;

/**
 * swagger2自动配置
 * @author hejian
 *
 */
@Configuration
@ConditionalOnProperty(prefix="spring.swagger2",name="enabled",havingValue="true")
@EnableConfigurationProperties({
	ISwagger2Properties.class
})
@EnableSwagger2
public class ISwagger2AutoConfigure {
	private static final Logger logger = LoggerFactory.getLogger(ISwagger2AutoConfigure.class);
	
	private ISwagger2Properties swagger2Properties;
	
	@Autowired
	public void setSwagger2Properties(ISwagger2Properties swagger2Properties) {
		this.swagger2Properties = swagger2Properties;
	}

	@Bean
	@ConditionalOnMissingBean(Docket.class)
    public Docket createRestApi() {
		logger.debug("created rest api");
		
		//api包选择器
		String basePackages = swagger2Properties.getBasePackages();
		Predicate<RequestHandler> selector = RequestHandlerSelectors.any();
		if(basePackages!=null && basePackages.trim().length()>0) {
			selector = ISwagger2AutoConfigure.basePackage(basePackages);
		}
		
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(selector)
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swagger2Properties.getTitle()) //标题
                .description(swagger2Properties.getDescription())
                .termsOfServiceUrl(swagger2Properties.getTermsOfServiceUrl())//服务条款网址
                .contact(swagger2Properties.getContact().getContact())//设置文档的联系方式
                .version(swagger2Properties.getVersion())
                .license(swagger2Properties.getLicense())
                .licenseUrl(swagger2Properties.getLicense())
                .build();
    }
	
    /**
     * Predicate that matches RequestHandler with given base package name for the class of the handler method.
     * This predicate includes all request handlers matching the provided basePackage
     *
     * @param basePackages - base package of the classes
     * @return this
     */
    public static Predicate<RequestHandler> basePackage(final String basePackages) {
        return new Predicate<RequestHandler>() {
            @Override
            public boolean apply(RequestHandler input) {
                return declaringClass(input).transform(handlerPackage(basePackages)).or(true);
            }
        };
    }
    
    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
      
    /** 
     * 处理包路径配置规则,支持多路径扫描匹配以逗号隔开
     * 
     * @param basePackage 扫描包路径
     * @return Function
     */  
    private static Function<Class<?>, Boolean> handlerPackage(final String basePackages) {
        return new Function<Class<?>, Boolean>() {
            @Override
            public Boolean apply(Class<?> input) {
            	String[] splitedPackge = basePackages.split(",");
                for (String strPackage : splitedPackge) {
                    boolean isMatch = input.getPackage().getName().startsWith(strPackage.trim());
                    if (isMatch) {
                        return true;
                    }
                }
                return false;
            }
        };
    }
	
	
}
